import { useUserStore } from '@/stores/modules/user'
import axios from 'axios'
import { cancelRequest } from './cancelRequest'

const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000,
})

request.interceptors.request.use((config) => {
  const token = useUserStore().token
  if (token) config.headers.token = token
  cancelRequest.addPendingRequest(config)
  return config
})

request.interceptors.response.use(
  (response) => {
    cancelRequest.removePending(response.config)
    return response.data
  },
  (error) => {
    if (!axios.isCancel(error)) {
      cancelRequest.removePending(error.config)
    }
    return Promise.reject(error)
  },
)

export default request
